package com.frxuexi.mine.ui

import android.annotation.SuppressLint
import android.text.TextUtils
import android.util.Log
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.BaseApp
import com.frxuexi.lib_base.NavPath
import com.frxuexi.lib_base.UiState
import com.frxuexi.lib_base.room.AppDataBase
import com.frxuexi.lib_base.room.UseRepository
import com.frxuexi.mine.R
import com.frxuexi.mine.intent.UserIntent
import com.frxuexi.mine.viewmodel.UserViewModel
import com.frxuexi.mine.viewmodel.UserViewModelFactory
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch


@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun LoginPage(navHostController: NavHostController,scope:CoroutineScope= rememberCoroutineScope()) {
    var name by remember {
        mutableStateOf("admin")
    }
    var pass by remember {
        mutableStateOf("666")
    }
    val vm by lazy {
        UserViewModelFactory(UseRepository(AppDataBase.getInstance(BaseApp.context))).create(
            UserViewModel::class.java
        )
    }

    scope.launch {
        vm.uiState.collect{
            when(it){
                is UiState.onSuccess->{
                    Log.i("===","登录成功")
                    MMKV.defaultMMKV().encode("name",name)
                    navHostController.popBackStack()
                }
                else->{

                }
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp, 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        var myModifier = Modifier.fillMaxWidth()
        Icon(
            imageVector = Icons.Default.ArrowBack,
            contentDescription = "",
            modifier = Modifier.clickable {
                navHostController.popBackStack()
            })
        Spacer(modifier = Modifier.height(40.dp))
        Text(text = "登录", fontSize = 22.sp, fontWeight = FontWeight.Bold)
        Text(text = "健康生活,从运动开始！")
        OutlinedTextField(
            value = name, onValueChange = { name = it },
            label = { Text(text = "用户名") },
            leadingIcon = {
                Icon(imageVector = Icons.Default.AccountCircle, contentDescription = "")
            }, modifier = myModifier
        )
        OutlinedTextField(
            value = pass, onValueChange = { pass = it },
            label = { Text(text = "密码") },
            leadingIcon = {
                Icon(imageVector = Icons.Default.Lock, contentDescription = "")
            },
            trailingIcon = {
                Icon(
                    painter = painterResource(id = R.drawable.ic_action_novisbily),
                    contentDescription = ""
                )
            },
            visualTransformation = PasswordVisualTransformation(),
            modifier = myModifier
        )
        Text(text = "忘记密码？", modifier = Modifier
            .offset(x = 280.dp)
            .clickable { Log.i("===", "点击") })
        Spacer(modifier = Modifier.height(40.dp))
        Button(
            onClick = {
                login(name, pass,vm)
            },
            colors = ButtonDefaults.buttonColors(containerColor = Color.Blue),
            modifier = myModifier.height(50.dp)
        ) {
            Text(text = "登录")
        }
//        Divider(modifier = Modifier.width(1.dp).height(20.dp))
        Row(
            Modifier
                .fillMaxWidth()
                .padding(bottom = 30.dp)
                .fillMaxHeight(),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.Bottom
        ) {
            Text(text = "没有账号？")
            Text(text = "去注册", color = Color.Blue, modifier = Modifier.clickable {
                navHostController.navigate(NavPath.REGISTER)
            })
        }


    }
}

fun login(name: String, pass: String, vm:UserViewModel) {
    if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
        ToastUtils.showLong("用户名和密码不能为空")
        return
    }
    if (!name.matches(Regex("[A-z0-9_#]{3,10}"))) {
        ToastUtils.showLong("不是合法用户名")
        return
    }
    vm.sendIntent(UserIntent.login(name, pass))
}